<template>
  <view class="shop-container">
    <!-- 顶部搜索栏 -->
    <view class="top-setion">
      <search-bar></search-bar>
      <!-- PLUS会员卡片 -->
      <view style="margin-top: 30rpx">
        <PlusMember />
      </view>
    </view>

    <!-- 活动广告轮播 -->
    <view class="activity-banner-box">
      <!-- <ActivityBanner /> -->
      <view class="activity-banner" v-for="(item, index) in activityBannerList" :key="index">
        <image :src="item.image" mode="widthFix"></image>
      </view>

    </view>

    <scroll-view class="bottom-section" scroll-y  @refresherrefresh="onRefresh"
      refresher-enabled :refresher-triggered="isRefreshing">


      <!-- 分类导航 -->
      <view class="category-nav-box">
        <view class="category-nav" :style="`width:${200 * categories.length}rpx`">
          <view :class="['nav-item', index === currentIndex ? 'active' : '']" v-for="(category, index) in categories"
            :key="index" @tap="onCategoryTap(category, index)">
            {{ category.spuTypeName }}
          </view>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="product-list">
        <view v-if="products.length > 0" class="product-item" v-for="(product, index) in products" :key="index" @tap="onProductTap(product)">
          <image class="product-image" :src="product.defaultSku.smallPhoto" mode="aspectFill"></image>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <view class="product-content">
              <view class="product-price">
                <text class="currency">¥</text>
                <text class="amount">{{ product.defaultSku.realPrice }}</text>
              </view>
              <view class="cart-btn">
                <uni-icons type="cart" size="20" color="#fff"></uni-icons>
              </view>
            </view>
          </view>
        </view>
        <view v-else class="no-data">该分类下暂无商品</view>
      </view>

      <!-- 加载状态 -->
      <view class="loading-status" v-if="products.length > 0">
        <text v-if="loading">加载中...</text>
        <text v-else-if="hasMore" class="load-more" @tap="onReachBottom">点击查看更多好物</text>
        <text v-else>没有更多数据</text>
      </view>

    </scroll-view>

    <!-- 底部内容 -->
    <footer-content :footerStyle="{ background: '#EDEDE4' }" />
    <!-- 底部导航栏 -->
    <tab-bar />
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import PlusMember from "@/components/PlusMember.vue";
import SearchBar from "@/components/SearchBar.vue";
import TabBar from "@/components/TabBar.vue";
import { getGoodsTypeAPI, getGoodsListAPI } from "@/apis/shop";
import { useCommonStore } from "@/store";

const commonStore = useCommonStore();
const currentIndex = ref(0);
const categories = ref([]);
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

const products = ref([]);
const loading = ref(false);
const hasMore = ref(true);
const isRefreshing = ref(false);

const activityBannerList = ref([
  {
    image: commonStore.baseImageUrl + 'test-yujia/shop/shop-item1.png',
  },
  {
    image: commonStore.baseImageUrl + 'test-yujia/shop/shop-item2.png',
  },
  {
    image: commonStore.baseImageUrl + 'test-yujia/shop/shop-item3.png',
  },

])

const fetchProducts = async (keyword, isRefresh = false) => {
  if (!hasMore.value && !isRefresh) return;

  const { branchCode } = commonStore.storeAndCityInfo;
  const spuType = categories.value[currentIndex.value].spuType;

  const params = {
    branchCode,
    page: isRefresh ? 1 : pagination.page,
    limit: pagination.limit,
    spuType,
  };

  if (keyword) {
    params.spuName = keyword;
  }

  try {
    loading.value = true;
    const { code, data } = await getGoodsListAPI(params);
    if (code === '200') {
      pagination.total = data.totalCount;
      if (isRefresh) {
        products.value = data.list;
        pagination.page = 1;
      } else {
        products.value = [...products.value, ...data.list];
      }
      hasMore.value = products.value.length < pagination.total;
    }
  } catch (error) {
    uni.showToast({
      title: "获取商品列表失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
    if (isRefresh) {
      isRefreshing.value = false;
    }
  }
};

const onCategoryTap = (category, index) => {
  currentIndex.value = index;
  hasMore.value = true;
  pagination.page = 1;
  products.value = [];
  fetchProducts();
};

const onProductTap = (product) => {
  const { branchCode } = commonStore.storeAndCityInfo;
  // 跳转到商品详情页
  uni.navigateTo({
    url: `/pages/subpackages/shopCenter/goods-detail?spuCode=${product.spuCode}&branchCode=${branchCode}`,
  });
};

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true;
  hasMore.value = true;
  fetchProducts(null, true);
};

// 触底加载更多
const onReachBottom = () => {
  if (loading.value || !hasMore.value) return;
  pagination.page++;
  fetchProducts();
};

const getGoodsType = async () => {
  try {
    const { data, code } = await getGoodsTypeAPI();
    console.log("商品类型：", data);
    categories.value = data;
    fetchProducts();
  } catch (error) {
    uni.showToast({
      title: "获取商品类型失败",
      icon: "none",
    });
  }
};

onMounted(() => {
  getGoodsType();
});
</script>

<style lang="scss" scoped>
.shop-container {
  min-height: 100vh;
  background: #edede4;
  box-sizing: border-box;
  padding-bottom: 120rpx;
  display: flex;
  flex-direction: column;

  .top-setion {
    background: linear-gradient(to bottom, #8cb22c, #e5e9cb);
    padding: 30rpx;
    flex-shrink: 0;
  }

  .activity-banner-box {
    box-sizing: border-box;
    padding: 0 30rpx;
    margin-bottom: 30rpx;
    display: flex;
    justify-content: space-between;

    .activity-banner {
      image {
        width: 220rpx;
        height: 150rpx;
      }
    }
  }

  .bottom-section {
    background: #eaebd8;
    flex: 1;
    box-sizing: border-box;
    padding: 0 30rpx;
  }

  .category-nav-box {
    display: flex;
    width: 100%;
    overflow: hidden;
    padding: 30rpx 0;

    .category-nav {
      display: flex;
      gap: 60rpx;
      flex-wrap: nowrap;
      overflow-x: auto;

      .nav-item {
        font-size: 30rpx;
        flex-shrink: 0;
        color: #9c9c93;

        &.active {
          color: #222222;
        }
      }
    }
  }

  .product-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 20rpx;
    box-sizing: border-box;

    .product-item {
      width: 300rpx;
      background: #fff;
      border-radius: 8px;
      margin-bottom: 15px;
      overflow: hidden;

      .product-image {
        width: 100%;
        height: 300rpx;
        background-color: #eee;
      }

      .product-info {
        padding: 10px;
        position: relative;

        .product-name {
          font-size: 14px;
          color: #333;
          line-height: 1.3;
          height: 36px;
          overflow: hidden;
          word-break: break-all;
          text-overflow: ellipsis;
        }

        .product-content {
          display: flex;
          // margin-top: 46rpx;
          justify-content: space-between;
          align-items: center;

          .product-price {
            margin-top: 5px;
            color: #add21e;

            .currency {
              font-size: 12px;
            }

            .amount {
              font-size: 16px;
              font-weight: bold;
            }
          }

          .cart-btn {
            width: 36rpx;
            height: 36rpx;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: url("https://siyuan-wx-1251107588.cos.ap-beijing.myqcloud.com/sy-qing-chaungye/test-yujia/shop/car@2x.png") no-repeat center center;
            background-size: 100% 100%;
          }
        }
      }
    }
    .no-data{
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #7d7d7d;
      text-align: center;
      margin: 0 auto;
    }
  }

  .loading-status {
    padding: 10rpx;
    box-sizing: border-box;
    text-align: center;
    color: #7d7d7d;
    font-size: 14px;

    .load-more{
      color: #7d7d7d;
      font-size: 28rpx;
      background-color: #ADD21E;
      display: flex;
      height: 84rpx;
      align-items: center;
      justify-content: center;
      border-radius: 10rpx;
    }
  }
}
</style>